$(function() {

	/**
	 * 首页文章列表
	 */
	var FIRST_PAGE = 1;
	var $articles = $('#articles');
	var $firstPage = $('#firstPage');
	var $prePage = $('#prePage');
	var $nextPage = $('#nextPage');
	var $lastPage = $('#lastPage');
	var $pageNumber = $('#pageNumber');
	var $totalPage = $('#totalPage');
	var $totalRow = $('#totalRow');

	function listArticle(pageNumber) {
		common.ajax($articles, 'listArticle?pageNumber=' + pageNumber, function(data) {
			var result = data.result;
			common.render($articles, $('#articlesTpl'), {
				articles: result.list
			});

			/**
			 * 首页文章的分页处理
			 */
			// 分页按钮的相关事件处理
			$firstPage.off('click').click(function() {
				clearPreContent();
				listArticle(FIRST_PAGE);
			});
			$prePage.off('click').click(function() {
				clearPreContent();
				listArticle(result.prePage);
			});
			$nextPage.off('click').click(function() {
				clearPreContent();
				listArticle(result.nextPage);
			});
			$lastPage.off('click').click(function() {
				clearPreContent();
				listArticle(result.totalPage);
			});
			// 更新分页的信息显示
			$pageNumber.html(result.pageNumber);
			$totalPage.html(result.totalPage);
			$totalRow.html(result.totalRow);
			// 控制分页按钮点击
			if ($pageNumber.html() == '1') {
				$firstPage.prop('disabled', true);
				$prePage.prop('disabled', true);
			} else {
				$firstPage.prop('disabled', false);
				$prePage.prop('disabled', false);
			}
			if ($pageNumber.html() == result.totalPage) {
				$nextPage.prop('disabled', true);
				$lastPage.prop('disabled', true);
			} else {
				$nextPage.prop('disabled', false);
				$lastPage.prop('disabled', false);
			}
			// AJAX请求数据显示前先清空页面原有的数据
			function clearPreContent() {
				$articles.children('li').remove();
			}

		});
	}
	listArticle(FIRST_PAGE);

	/**
	 * 首页左侧阅读排行
	 */
	var $readRanks = $('#readRanks');
	common.ajax($readRanks, 'listReadRank', function(data) {
		common.render($readRanks, $('#readRankTpl'), {
			readRanks: data.result
		});
	})

});